package com.uml.umlwork.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.uml.umlwork.dto.student.UpdateStudentInfoDTO;
import com.uml.umlwork.entity.Class;
import com.uml.umlwork.entity.CourseSelect;
import com.uml.umlwork.entity.Student;
import com.uml.umlwork.entity.enumeration.GenderEnum;
import com.uml.umlwork.mapper.ClassMapper;
import com.uml.umlwork.mapper.CourseSelectMapper;
import com.uml.umlwork.mapper.StudentMapper;
import com.uml.umlwork.service.StudentService;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @author Siki
 * @date 2020/12/22
 */
@Service
public class StudentServiceImpl implements StudentService {

    private final StudentMapper studentMapper;
    private final ClassMapper classMapper;
    private final CourseSelectMapper courseSelectMapper;

    public StudentServiceImpl(StudentMapper studentMapper, ClassMapper classMapper, CourseSelectMapper courseSelectMapper) {
        this.studentMapper = studentMapper;
        this.classMapper = classMapper;
        this.courseSelectMapper = courseSelectMapper;
    }

    @Override
    public void updateInformation(UpdateStudentInfoDTO dto, String id) {
        var student = getStudentByUserId(id);
        student.setAge(dto.getAge())
                .setEduLevel(dto.getEduLevel())
                .setEmail(dto.getEmail())
                .setJob(dto.getJob())
                .setGender(GenderEnum.valueOf(dto.getGender()));
        studentMapper.updateById(student);
    }

    @Override
    public void selectClass(Integer studentId, Integer classId) {

        //查询该班级是否设置课程，若未设置课程则不能选课
        Class clazz = classMapper.selectOne((new QueryWrapper<Class>()).lambda()
                .eq(Class::getId, classId)
                .isNotNull(Class::getCourseId));

        if (clazz == null){
            throw new RuntimeException("该班级没有课程信息");
        }

        CourseSelect courseSelect = new CourseSelect();
        courseSelect.setClassId(classId);
        courseSelect.setStudentId(studentId);

        courseSelectMapper.insert(courseSelect);

    }

    @Override
    public Integer getStudentIdByUserId(String userId) {
        Student student = studentMapper.selectOne(new QueryWrapper<Student>().eq("user_id",userId));
        return student.getId();
    }


    private Student getStudentByUserId(String id) {
        return Optional.ofNullable(studentMapper.selectOne(
                new QueryWrapper<Student>().eq("user_id", id))
        ).orElseThrow(() -> new RuntimeException("该id:" + id + "有误"));
    }
}
